package questions;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 * 多共享资源竞争
 * 线程并发数控制(本质也是资源竞争，争线程)
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(21);
        Random random= new Random(23);
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "  抢到车位");
                long ms = 0;
                try {
                    TimeUnit.MILLISECONDS.sleep(ms = (long) (Math.abs(random.nextLong())% 1000 + 300));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "  " + ms + "ms 后走了");
                semaphore.release();
            }, "汽车" + i).start();

        }
    }

}
